package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import retrieve.Retriever;
import retrieve.RetrieverManager;

import com.google.gson.Gson;


public class RetrieveJSONServlet extends HttpServlet{
    
	private RetrieverManager retrieverManager;
	private transient String curJson;
	
	public RetrieveJSONServlet() {
		retrieverManager = new RetrieverManager();
		retrieverManager.addRetriver("datamining-group", "131.94.130.167", 32165);
		startRetrieve();
	}
	
	private void startRetrieve() {
		retrieverManager.startAllRetrivers();
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
        doGet(request, response);
    }
    
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		String method = request.getParameter("method");
		if(method == null)
			return;
		if(method.equals("retrieveAllGroups")) {
			retrieveAllGroups(request, response);
		}
		else if(method.equals("retrieveAllNodes")) {
			retrieveAllNodes(request, response);
		}
		else if(method.equals("retrieveNodeMetaData")) {
			retrieveNodeMetaData(request, response);
		}

	}
	
	public void retrieveAllGroups(HttpServletRequest request, HttpServletResponse response) 
			throws IOException, ServletException {
		Set<String> groupNames = retrieverManager.getRetrieverNames();
		Gson gson = new Gson();
		String json = gson.toJson(groupNames);
		PrintWriter out = response.getWriter();
		out.println(json);
		out.close();
	}
	
	public void retrieveAllNodes(HttpServletRequest request, HttpServletResponse response) 
			throws IOException, ServletException {
		String groupName = request.getParameter("groupname");
		List<String> nodeNames = retrieverManager.getAllNodesByRetrieverName(groupName);
		Gson gson = new Gson();
		String json = gson.toJson(nodeNames);
		PrintWriter out = response.getWriter();
		out.println(json);
		out.close();
	}
	
	public void retrieveNodeMetaData(HttpServletRequest request, HttpServletResponse response) 
			throws IOException, ServletException {
		String groupName = request.getParameter("groupname");
		String nodeName = request.getParameter("nodename");
		PrintWriter out = response.getWriter();
		String nodeJson = retrieverManager.getRetriever(groupName).getJsonByNodeName(nodeName);
		System.out.println(nodeJson);
		out.println(nodeJson);
		out.close();
	}
	
}
